package com.funtl.screw.codegen.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.smallbun.screw.boot.config.Screw;
import cn.smallbun.screw.boot.properties.ScrewProperties;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.funtl.screw.codegen.entity.ColumnEntity;
import com.funtl.screw.codegen.entity.GenConfig;
import com.funtl.screw.codegen.service.GenTableColumnService;
import com.funtl.screw.codegen.service.GeneratorService;
import com.funtl.screw.common.core.util.QueryRequest;
import com.funtl.screw.common.core.util.ResponseResult;
import com.funtl.screw.common.core.util.SpringContextHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author Lusifer
 * @since 2023-01-30
 */
@RestController
@AllArgsConstructor
@Api(value = "datasource", tags = "代码生成")
@RequestMapping("/generator")
public class GeneratorController {

    private final Screw screw;

    private final GeneratorService generatorService;

    private final GenTableColumnService columnService;

    /**
     * 列表
     *
     * @param tableName 参数集
     * @param dsName    数据源编号
     * @return 数据库表
     */
    @ApiOperation(value = "分页查询表")
    @GetMapping("/page")
    public ResponseResult<IPage<Map<String, Object>>> getPage(QueryRequest queryRequest, String tableName, String dsName) {
        return ResponseResult.ok(generatorService.getPage(queryRequest, tableName, dsName));
    }

    /**
     * 预览代码
     */
    @ApiOperation(value = "预览代码")
    @GetMapping("/preview")
    public ResponseResult<Map<String, Map<String, String>>> previewCode(GenConfig genConfig) {
        return ResponseResult.ok(generatorService.previewCode(genConfig));
    }

    /**
     * 查询表的列信息
     */
    @ApiOperation(value = "查询表的列信息")
    @GetMapping("/table")
    public ResponseResult<IPage<ColumnEntity>> getTable(QueryRequest queryRequest, GenConfig genConfig) {
        return ResponseResult.ok(columnService.listTable(queryRequest, genConfig));
    }

    /**
     * 生成代码
     *
     * @param genConfig 数据表配置
     */
    @ApiOperation(value = "生成代码")
    @SneakyThrows
    @PostMapping("/code")
    public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
        byte[] data = generatorService.generatorCode(genConfig);
        response.reset();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                String.format("attachment; filename=%s.zip", genConfig.getTableName()));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }

    @ApiOperation(value = "导出数据库文档")
    @SneakyThrows
    @GetMapping("/doc")
    public void generatorDoc(String[] tableNames, String dsName, HttpServletResponse response) {
        // 设置指定的数据源
        DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
        DynamicDataSourceContextHolder.push(dsName);
        DataSource dataSource = dynamicRoutingDataSource.determineDataSource();

        // 设置指定的目标表
        ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class);
        screwProperties.setDesignatedTableName(CollUtil.toList(tableNames));

        // 生成
        byte[] data = screw.documentGeneration(dataSource, screwProperties).toByteArray();
        response.reset();
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }

}
